package com.zdltech.lightappupdatelib.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.widget.Toast;

import com.zdltech.lightappupdatelib.core.LightConstant;
import com.zdltech.lightappupdatelib.R;
import com.zdltech.lightappupdatelib.entity.AppVertionEntity;
import com.zdltech.lightappupdatelib.net.HttpCoreManager;
import com.zdltech.lightappupdatelib.net.HttpManager;
import com.zdltech.lightappupdatelib.utils.LightAppUpdateUtils;

import java.io.File;


/**
 * 后台下载
 */
public class DownloadService extends Service {

    private static final int NOTIFY_ID = 0;
    private static final String TAG = DownloadService.class.getSimpleName();
    public static boolean isRunning = false;
    private NotificationManager mNotificationManager;
    private DownloadBinder binder = new DownloadBinder();
    private NotificationCompat.Builder mBuilder;
        /**
     * 开启服务方法
     *
     * @param context
     */
    public static void startService(Context context,AppVertionEntity entity) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra("item",entity);
        context.startService(intent);
    }
    private boolean mDismissNotificationProgress = false;

    public static void bindService(Context context, ServiceConnection connection) {
        Intent intent = new Intent(context, DownloadService.class);
        context.startService(intent);
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
        isRunning = true;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (LightAppUpdateUtils.rootFile==null){//默认设置
            LightAppUpdateUtils.rootFile = getFilesDir().getAbsolutePath();//获取文件决定路径
        }

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        AppVertionEntity updateApp = (AppVertionEntity) intent.getSerializableExtra(LightConstant.INTENT_ITEM);
        if (updateApp!=null){
            startDownload(updateApp, null);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 返回自定义的DownloadBinder实例
        return binder;
    }

    @Override
    public void onDestroy() {
        mNotificationManager = null;
        super.onDestroy();
    }

    /**
     * 创建通知
     */
    private void setUpNotification() {
        if (mDismissNotificationProgress) {
            return;
        }

        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("开始下载")
                .setContentText("正在连接服务器")
                .setSmallIcon(R.mipmap.lib_update_app_update_icon)
                .setLargeIcon(LightAppUpdateUtils.drawableToBitmap(LightAppUpdateUtils.getAppIcon(DownloadService.this)))
                .setOngoing(true)
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis());
        mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
    }

    /**
     * 下载模块
     */
    private void startDownload(AppVertionEntity updateApp, final DownloadCallback callback) {
        if (!"apk".equals(updateApp.getUpdateType())){//文件格式不正确
            return;
        }
        mDismissNotificationProgress = updateApp.ismDismissNotificationProgress();
        String apkUrl = updateApp.getUpdateUrl();
        if (TextUtils.isEmpty(apkUrl)) {
            String contentText = "新版本下载路径错误";
            stop(contentText);
            return;
        }
        String appName = LightAppUpdateUtils.getApkName(updateApp);
        String taget ="";
        try {
            taget = LightAppUpdateUtils.getAppFilePath(updateApp);
        }catch (Exception e){
            e.printStackTrace();
        }
        HttpCoreManager.getInstance().download(apkUrl,taget , appName, new FileDownloadCallBack(callback));
    }

    private void stop(String contentText) {
        if (mBuilder != null) {
            mBuilder.setContentTitle(LightAppUpdateUtils.getAppName(DownloadService.this)).setContentText(contentText);
            Notification notification = mBuilder.build();
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(NOTIFY_ID, notification);
        }
        close();
    }

    private void close() {
        stopSelf();
        isRunning = false;
    }


    /**
     * DownloadBinder中定义了一些实用的方法
     *
     * @author user
     */
    public class DownloadBinder extends Binder {
        /**
         * 开始下载
         *
         * @param updateApp 新app信息
         * @param callback  下载回调
         */
        public void start(AppVertionEntity updateApp, DownloadCallback callback) {
            //下载
            startDownload(updateApp, callback);
        }
    }

    class FileDownloadCallBack implements HttpManager.FileCallback {
        private final DownloadCallback mCallBack;
        int oldRate = 0;

        public FileDownloadCallBack(@Nullable DownloadCallback callback) {
            super();
            this.mCallBack = callback;
        }

        @Override
        public void onBefore() {
            //初始化通知栏
            setUpNotification();
            if (mCallBack != null) {
                mCallBack.onStart();
            }
        }

        @Override
        public void onProgress(float progress, long total) {
            //做一下判断，防止自回调过于频繁，造成更新通知栏进度过于频繁，而出现卡顿的问题。
            int rate = Math.round(progress * 100);
            if (oldRate != rate) {
                if (mCallBack != null) {
                    mCallBack.setMax(total);
                    mCallBack.onProgress(progress, total);
                }

                if (mBuilder != null) {
                    mBuilder.setContentTitle("正在下载：" + LightAppUpdateUtils.getAppName(DownloadService.this))
                            .setContentText(rate + "%")
                            .setProgress(100, rate, false)
                            .setWhen(System.currentTimeMillis());
                    Notification notification = mBuilder.build();
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    mNotificationManager.notify(NOTIFY_ID, notification);
                }

                //重新赋值
                oldRate = rate;
            }


        }

        @Override
        public void onError(String error) {
            Toast.makeText(DownloadService.this, "更新新版本出错，" + error, Toast.LENGTH_SHORT).show();
            //App前台运行
            if (mCallBack != null) {
                mCallBack.onError(error);
            }
            try {
                mNotificationManager.cancel(NOTIFY_ID);
                close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        @Override
        public void onResponse(File file) {
            mDismissNotificationProgress = false;
            if (mCallBack != null) {
                if (!mCallBack.onFinish(file)) {
                    close();
                    return;
                }
            }

            if (LightAppUpdateUtils.isAppOnForeground(DownloadService.this) || mBuilder == null) {
                //App前台运行
                mNotificationManager.cancel(NOTIFY_ID);
                LightAppUpdateUtils.installApp(DownloadService.this, file);
            } else {
                //App后台运行
                //更新参数,注意flags要使用FLAG_UPDATE_CURRENT
                Intent installAppIntent = LightAppUpdateUtils.getInstallAppIntent(DownloadService.this, file);
                PendingIntent contentIntent = PendingIntent.getActivity(DownloadService.this, 0, installAppIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(contentIntent)
                        .setContentTitle(LightAppUpdateUtils.getAppName(DownloadService.this))
                        .setContentText("下载完成，请点击安装")
                        .setProgress(0, 0, false)
//                        .setAutoCancel(true)
                        .setDefaults((Notification.DEFAULT_ALL));
                Notification notification = mBuilder.build();
                notification.flags = Notification.FLAG_AUTO_CANCEL;
                mNotificationManager.notify(NOTIFY_ID, notification);
            }
            //下载完自杀
            close();
        }
    }
}
